// pages/work-order/executeRecord/index.ts
const app = getApp()
Page({
  data: {
    expand: false,
    showTypeSelector: false,
    currentType: { name: '其他', key: 'userList', index: 3 },
    customerList: [],
    deviceList: [],
    itemList: [],
    userList: [],
    selectList: [],
    workOrderID: null,
    title: '工单创建',
    typeList: [
      { name: '其他', key: 'userList', index: 3 },
      { name: '项目', key: 'itemList', index: 1 },
      { name: '设备', key: 'deviceList', index: 6 },
      { name: '客户', key: 'customerList', index: 2 }
    ],
    /*  formData ⬇️ */
    formData: {
      op: "ajaxWorkOrderAdd",
      name: '',//标题
      others: '',//备注
      level: 1,//紧急程度
      type: 3,//工单类型 关联类型 1项目 2客户 3维修 6设备
      status: 0,
      parters: '',//协办人
      ftime: '',//计划完成时间
      exuserid: '',//执行人
      cusid: '',//关联客户id
      itemid: '',//关联项目id
      payid: '',
      repairid: '',//关联维修id
      did: '',//设备id
      warrid: '',//通过告警生成id
      zaddr: '',//执行地址
      lng: '',
      lat: '',
      flowpath: '1',//是否固定流程
      imgs: '',
      videos: '',
      files: '',
      fileNames: {},
      zmode: '1',//工单类型区分 1通用工单 2维修工单 3合同工单
      zconid: '0',//工单类型关联的对应模块id
      detaddr: '',//详细地址门牌号      
    },
    /*  formData ⬆️ */
  },
  onLoad(option) {
    if (option.id) {
      console.log(option.id)
      this.setData({
        title: '工单编辑',
      })
    }
    // 用Promise.all保证数据加载顺序
    Promise.all([
      this.getCustomerList(),
      this.getDeviceItemList(),
      this.getUserList()
    ]).then(() => {
      if (option.id) {
        this.setData({
          workOrderID: option.id,
        })
        this.getWorkOrderInfo() // 数据加载完成后执行
      }
    })
  },
  getCustomerList() {
    return app.axios('customer', { op: 'ajaxCustomerList' }).then(res => {
      if (res.code && res.lists) {
        this.setData({ customerList: res.lists.map(item => ({ ...item, selected: false })) })
      }
      return res // 返回结果用于Promise链
    })
  },

  getDeviceItemList() {
    return app.axios('item', { op: 'ajaxGroupDcAll2' }).then(res => {
      if (res.code && res.lists) {
        this.setData({
          itemList: res.lists.filter(item => item?.zztype === 1).map(i => ({ ...i, selected: false })),
          deviceList: res.lists.filter(item => item?.zztype === 2).map(i => ({ ...i, selected: false }))
        })
      }
      return res
    })
  },

  getUserList() {
    return app.axios('user', { op: 'ajaxUserDlList' }).then(res => {
      if (res.code && res.lists) {
        this.setData({ userList: res.lists.map(item => ({ ...item, selected: false })) })
      }
      return res
    })
  },
  // 新增 - 根据接口返回设置选中状态
  setSelectedStatus(itemData) {
    const updates = {}

    // 设置客户选中
    if (itemData.cusid) {
      updates.customerList = this.data.customerList.map(c =>
        ({ ...c, selected: c.id === itemData.cusid })
      )
    }

    // 设置项目选中
    if (itemData.itemid) {
      updates.itemList = this.data.itemList.map(i =>
        ({ ...i, selected: i.id === itemData.itemid })
      )
    }

    // 设置设备选中
    if (itemData.did) {
      updates.deviceList = this.data.deviceList.map(d =>
        ({ ...d, selected: d.id === itemData.did })
      )
    }

    // 设置执行人选中
    if (itemData.exuserid) {
      updates.userList = this.data.userList.map(u =>
        ({ ...u, selected: u.id === itemData.exuserid })
      )
    }

    this.setData(updates)
  },
  getWorkOrderInfo() {
    app.axios('workOrder', {
      op: 'ajaxWorkOrderDetail',
      id: this.data.workOrderID, // 使用动态ID
    }).then(res => {
      if (res.code && res.item) {
        // 更新表单数据
        this.setData({
          'formData': {
            ...this.data.formData,
            ...res.item,
            // 特殊字段处理（根据接口实际数据结构调整）
            cusid: res.item.cusid || '',
            itemid: res.item.itemid || '',
            did: res.item.did || '',
            exuserid: res.item.exuserid || ''
          }
        })

        // 设置选中状态
        this.setSelectedStatus(res.item)
      }
    })
  },
  handleSelectItem(e) {
    const selectedId = e.currentTarget.dataset.id;
    const newList = this.data.selectList.map(item => {
      // 当前点击项设为 true，其他项设为 false
      return { ...item, selected: item.id === selectedId };
    });

    this.setData({
      selectList: newList
    });

    console.log("当前选中项ID:", selectedId);
  },
  bindKeyInput(e) {
    let field = e.currentTarget.dataset.field
    this.setData({
      formData: {
        ...this.data.formData, // 先展开原有数据
        [field]: e.detail.value // 动态设置字段值（关键语法）
      }
    })
  },
  navigateTo(e) {
    app.navigateTo(e.currentTarget.dataset.url, e.currentTarget.dataset.type)
  },
  toggleExpand() {
    this.setData({ expand: !this.data.expand })
  },
  toggleTypeSelector() {
    this.setData({ showTypeSelector: !this.data.showTypeSelector })
  },
  changeType(e) {
    const selected = e.currentTarget.dataset.item;
    this.setData({
      currentType: selected,
      'formData.type': selected.index
    })
  },
  togglePicker(e) {
    const type = e.currentTarget.dataset.type
    // 直接调用组件方法（需获取实例）
    const picker = this.selectComponent(`#list-picker-${type}`)
    picker.togglePicker()
  },
  toggleSelector() {
    // 直接调用组件方法（需获取实例）
    const drawer = this.selectComponent('#v-drawer-addGD')
    drawer.toggleDrawer()
  },
  toggleMapMarker() {
    const mapMarker = this.selectComponent('#v-map')
    mapMarker.toggleMapMarker()
  },
  toggleDatePicker() {
    // 直接调用组件方法（需获取实例）
    const datePicker = this.selectComponent('#date-picker')
    datePicker.toggleDatePicker()
  },
  comitResult(res) {
    this.setData({
      formData: {
        ...this.data.formData, // 先展开原有数据
        zaddr: res.detail.selectedAddress, // 动态设置字段值
        useraddr: res.detail.userAddress, // 动态设置字段值
        lng: res.detail.selectedLocation.longitude, // 动态设置字段值
        lat: res.detail.selectedLocation.latitude, // 动态设置字段值
      }
    })
  },
  confirmDate(e) {
    console.log(e.detail)
    this.setData({
      'formData.ftime': e.detail.formatted
    })
  },
  handleCustomerConfirm(e) {
    const selectedItems = e.detail.selectedItems;
    if (selectedItems.length === 0) {
      wx.showToast({ title: '请选择客户', icon: 'none' });
      return;
    }
    const selected = selectedItems[0];
    this.setData({
      'formData.cusid': selected.id,
      'formData.cusName': selected.name
    });
  },

  handleUserConfirm(e) {
    const selectedItems = e.detail.selectedItems;
    if (selectedItems.length === 0) {
      wx.showToast({ title: '请选择执行人', icon: 'none' });
      return;
    }
    const selected = selectedItems[0];
    this.setData({
      'formData.exuserid': selected.id,
      'formData.exusername': selected.name
    });
  },

  handleItemConfirm(e) {
    const selectedItems = e.detail.selectedItems;
    if (selectedItems.length === 0) {
      wx.showToast({ title: '请选择项目', icon: 'none' });
      return;
    }
    const selected = selectedItems[0];
    this.setData({
      'formData.itemid': selected.id,
      'formData.itemName': selected.name
    });
  },

  handleDeviceConfirm(e) {
    const selectedItems = e.detail.selectedItems;
    if (selectedItems.length === 0) {
      wx.showToast({ title: '请选择设备', icon: 'none' });
      return;
    }
    const selected = selectedItems[0];
    // 设备数据结构特殊处理（假设设备名称字段为 label）
    this.setData({
      'formData.did': selected.id,
      'formData.dName': selected.label || selected.title // 根据实际数据结构调整
    });
  },
  submit() {
    const parmas = this.data.formData
    app.axios('workOrder', parmas)
      .then(res => {
        if (res.code) {
          wx.showToast({
            title: '工单创建成功'
          })
          setTimeout(() => {
            app.navigateTo('/pages/workOrderMain/index', 'switchTab')
          }, 500);
        }
      })
  }
})